package cn.lzit.request.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/ResultServlet")
public class ResultServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("username"); // 获取用户姓名
        String pwd = request.getParameter("password"); // 获取用户密码
        String age = request.getParameter("age"); // 获取用户年龄
        String sex = request.getParameter("sex"); // 获取用户性别
        String[] loves = request.getParameterValues("loves"); // 获取用户爱好
        String email = request.getParameter("email"); // 获取用户EAMIL
        String tel = request.getParameter("tel"); // 获取用户联系电话

        // 中文乱码处理，取决于你的tomcat版本和配置
        // 如果你的表单和Servlet都使用了UTF-8编码，并且Tomcat已经配置为支持UTF-8，则可能不需要这一步
        try {
            name = new String(name.getBytes("ISO-8859-1"), "UTF-8");
            if (age != null) {
                age = new String(age.getBytes("ISO-8859-1"), "UTF-8");
            }
            if (email != null) {
                email = new String(email.getBytes("ISO-8859-1"), "UTF-8");
            }
            if (tel != null) {
                tel = new String(tel.getBytes("ISO-8859-1"), "UTF-8");
            }
            for (int i = 0; i < loves.length; i++) {
                loves[i] = new String(loves[i].getBytes("ISO-8859-1"), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        response.setContentType("text/html;charset=UTF-8");

        PrintWriter pWriter = response.getWriter();
        pWriter.print("<body bgcolor='pink'>");

        // 密码长度验证
        if (pwd.length() < 6 || pwd.length() > 10) {
            pWriter.print("密码长度不符合要求（6-10个字符）<br/>");
        }

        // 显示用户的注册信息
        pWriter.print("用户名: " + name + "<br/>");
        pWriter.print("密码: " + pwd + "<br/>");
        pWriter.print("年龄: " + age + "<br/>");
        pWriter.print("性别: " + sex + "<br/>");
        pWriter.print("爱好: " + (loves != null ? String.join(", ", loves) : "无") + "<br/>");
        pWriter.print("Email: " + email + "<br/>");
        pWriter.print("Tel: " + tel + "<br/>");
        pWriter.print("</body>");
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}